import React from 'react';
import {Card, Form, Button, message, Icon, Switch, Input, TreeSelect, InputNumber} from 'antd';
import {connect} from 'dva';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {FormComponentProps} from 'antd/es/form';
import {ModelState} from './model';
import {Dispatch} from 'redux';
import {UploadChangeParam} from 'antd/lib/upload';
import {UploadFile} from 'antd/lib/upload/interface';
import router from "umi/router";
import {TreeNode} from "antd/lib/tree-select";


const FormItem = Form.Item;

// const {Option} = Select;

interface IProps extends FormComponentProps {
  menuSave: ModelState;
  loading: boolean;
  dispatch: Dispatch<any>;
  location: any;
  match: any;
}

interface IStates {
  selectedRowKeys: any[];
  formValues: object;
  previewImageUrl: string;
  preViewModalVisible: boolean;
}

const formItemLayout = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 8},
    md: {span: 3},
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 12},
    md: {span: 18},
  },
};
const submitFormLayout = {
  wrapperCol: {
    xs: {span: 24, offset: 0},
    sm: {span: 10, offset: 3},
  },
};

class Index extends React.Component<IProps, IStates> {
  state: IStates = {
    selectedRowKeys: [],
    formValues: {},
    previewImageUrl: '',
    preViewModalVisible: false,
  };

  componentDidMount() {
    const {dispatch, match} = this.props;
    const id = match.params.id;
    dispatch({
      type: 'menuSave/fetchDetail',
      payload: {id}
    });
  }


  UploadButton = (
    <div>
      <Icon type="plus"/>
      {/*<Icon type={this.state.loading ? 'loading' : 'plus'}/>*/}
      {/*<div className="ant-upload-text">头像上传</div>*/}
    </div>
  );

  //UploadChangeParam
  handleUploadChange = (info: UploadChangeParam): any => {
    let fileList = info.fileList;
    if (info.file.status === 'done') {
      message.success(`${info.file.name}文件上传成功`);
    }
    return fileList.slice(-1);
  };

  //UploadFile
  photoPreview = (file: UploadFile) => {
    const fileUrl = file.url || file.thumbUrl;
    this.setState({
      previewImageUrl: fileUrl as string,
      preViewModalVisible: true,
    });
  };

  previewModalCancel = () => {
    this.setState({
      preViewModalVisible: false,
    });
  };


  handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const {form, dispatch, match} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (!err) {
        // fieldsValue.avatar = fieldsValue.avatar.map((item: any) => ({
        //   uid: item.uid,
        //   name: item.name,
        //   url: item.url ? item.url : item.response.data.file_url
        // }));
        if (Array.isArray(fieldsValue.pid)) {
          fieldsValue.pid = 0;
        }
        dispatch({
          type: 'menuSave/addAndUpdate',
          payload: {id: match.params.id, ...fieldsValue}
        });
      }
    });
  };

  render() {
    const {form, menuSave: {detail, list}, loading, match} = this.props;
    const getFieldDecorator = form.getFieldDecorator;
    const routes = [
      {
        path: 'index',
        breadcrumbName: '主页',
      },
      {
        path: 'account',
        breadcrumbName: '账号管理',
      },
      {
        path: 'admin',
        breadcrumbName: '菜单管理',
      },
      {
        path: 'add',
        breadcrumbName: '添加菜单',
      },
    ];
    if (match.params.id > 0) {
      routes[routes.length - 1] = {
        path: 'save',
        breadcrumbName: '修改菜单',
      };
    }


    return (
      //@ts-ignore
      <PageHeaderWrapper title={false} breadcrumb={{routes}}>
        <Card bordered={false}>
          <Form layout="horizontal" {...formItemLayout} onSubmit={this.handleSubmit}>


            <FormItem label="名称">
              {getFieldDecorator('name', {
                rules: [
                  {
                    required: true,
                  },
                ],
                initialValue: detail.name || ''
              })(<Input placeholder={"请输入名称"} style={{width: 450}}/>)}
            </FormItem>

            <FormItem label={"父菜单"}>
              {
                getFieldDecorator('pid', {
                  initialValue: detail.pid || []
                })(
                  <TreeSelect
                    style={{width: 300}}
                    dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                    treeData={list as TreeNode[]}
                    placeholder="未选择则代表一级菜单"
                    treeDefaultExpandAll={false}
                  />
                )
              }

              <Button type={"default"} style={{marginLeft: 10}} onClick={() => {
                form.setFieldsValue({pid: []});
              }}>重置</Button>
            </FormItem>


            <FormItem label="路径">
              {getFieldDecorator('path', {
                rules: [
                  {
                    required: true,
                  },
                ],
                initialValue: detail.path || ''
              })(<Input placeholder={"请输入路径"} style={{width: 450}}/>)}
            </FormItem>


            <FormItem label="图标">
              {getFieldDecorator('icon', {
                rules: [
                  {
                    required: true,
                  },
                ],
                initialValue: detail.icon || ''
              })(<Input placeholder={"请输入图标"} style={{width: 150}}/>)}
            </FormItem>


            <FormItem label="显示">
              {getFieldDecorator('visible', {
                rules: [
                  {
                    required: true,
                  },
                ],
                valuePropName: 'checked',
                initialValue: detail.visible === undefined ? true : !!detail.visible
              })(<Switch checkedChildren="显示" unCheckedChildren="隐藏"/>)}
            </FormItem>

            <FormItem label="排序">
              {getFieldDecorator('sort', {
                initialValue: detail.sort || 0
              })(<InputNumber min={0} max={1000}/>)}
            </FormItem>


            <FormItem {...submitFormLayout}>
              <Button type="primary" htmlType="submit" loading={loading}>
                提交
              </Button>
              <Button style={{marginLeft: 8}} onClick={() => {
                router.goBack();
              }}>返回</Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<IProps>()(
  connect(
    ({
       menuSave,
       loading,
     }: {
      menuSave: ModelState;
      loading: {
        effects: { [key: string]: boolean }
      };
    }) => ({
      menuSave,
      loading: loading.effects['menuSave/addAndUpdate'],
    }),
  )(Index),
);
